<!doctype html><html lang=en-us><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=description content="规则  每个值都有一个称为其所有者的变量 同一时刻只能有一个所有者 当所有者离开作用域时，值被舍弃（调用 drop 函数）  变量与数据的交互 移动语义 Rust 从不自动进行变量的深层复制，而是使用移动语义。
lets1=String::from(&amp;#34;abc&amp;#34;);lets2=s1;// s1 is invalid 克隆语义 使用 clone 函数实现明确的深层复制。
lets1=String::from(&amp;#34;hello&amp;#34;);lets2=s1.clone();复制语义 诸如整数等类型数据，具有编译时已知的大小，并完全存储在栈上，能够快速复制，浅层复制与深层复制没有实际区别，不需要使用 clone 函数（实现 Copy 特征以标记这类数据）。
letx=5;lety=x;引用 lets1: String =String::from(&amp;#34;hello&amp;#34;);letref_s1: &amp;amp;String =&amp;amp;s1;letmutmut_s1: String =String::from(&amp;#34;hello&amp;#34;);letref_s1: &amp;amp;mutString=&amp;amp;mutmut_s1;&amp;amp; 表示引用变量，不取得变量的所有权，默认以不可变方式进行引用，&amp;amp;mut 表示可变方式引用。 传入引用变量的函数，称为借用了这个变量。
在同一作用域下，对同一个对象的引用，只允许以下组合方式：
 一个或多个不可变引用 一个可变引用，没有不可变引用  切片 切片指对一个序列中的一段连续元素的引用，不取得变量的所有权。
leta=[1,2,3,4,5];letslice=&amp;amp;a[1..3];assert_eq!(slice,&amp;amp;[2,3]);字符串切片 lets=String::from(&amp;#34;hello world&amp;#34;);lethello: &amp;amp;str =&amp;amp;s[0..5];letworld: &amp;amp;str =&amp;amp;s[6..11];letslice: &amp;amp;str =&amp;amp;s[..2];letslice: &amp;amp;str =&amp;amp;s[3..];letslice: &amp;amp;str =&amp;amp;s[..];字符串字面值的类型为字符串切片（&amp;amp;str）。
生存期 借用检查器会检查生存期长短关系，来保证借用安全。
fn main(){{letx=5;// ----------+-- &amp;#39;b // | letr=&amp;amp;x;// --+-- &amp;#39;a | // | | println!"><title>Rust 所有权特性</title><link rel=canonical href=https://stardustdl.gitee.io/posts/learning/rust-onwership/><link rel=stylesheet href=/scss/style.min.css><meta property="og:title" content="Rust 所有权特性"><meta property="og:description" content="规则  每个值都有一个称为其所有者的变量 同一时刻只能有一个所有者 当所有者离开作用域时，值被舍弃（调用 drop 函数）  变量与数据的交互 移动语义 Rust 从不自动进行变量的深层复制，而是使用移动语义。
lets1=String::from(&amp;#34;abc&amp;#34;);lets2=s1;// s1 is invalid 克隆语义 使用 clone 函数实现明确的深层复制。
lets1=String::from(&amp;#34;hello&amp;#34;);lets2=s1.clone();复制语义 诸如整数等类型数据，具有编译时已知的大小，并完全存储在栈上，能够快速复制，浅层复制与深层复制没有实际区别，不需要使用 clone 函数（实现 Copy 特征以标记这类数据）。
letx=5;lety=x;引用 lets1: String =String::from(&amp;#34;hello&amp;#34;);letref_s1: &amp;amp;String =&amp;amp;s1;letmutmut_s1: String =String::from(&amp;#34;hello&amp;#34;);letref_s1: &amp;amp;mutString=&amp;amp;mutmut_s1;&amp;amp; 表示引用变量，不取得变量的所有权，默认以不可变方式进行引用，&amp;amp;mut 表示可变方式引用。 传入引用变量的函数，称为借用了这个变量。
在同一作用域下，对同一个对象的引用，只允许以下组合方式：
 一个或多个不可变引用 一个可变引用，没有不可变引用  切片 切片指对一个序列中的一段连续元素的引用，不取得变量的所有权。
leta=[1,2,3,4,5];letslice=&amp;amp;a[1..3];assert_eq!(slice,&amp;amp;[2,3]);字符串切片 lets=String::from(&amp;#34;hello world&amp;#34;);lethello: &amp;amp;str =&amp;amp;s[0..5];letworld: &amp;amp;str =&amp;amp;s[6..11];letslice: &amp;amp;str =&amp;amp;s[..2];letslice: &amp;amp;str =&amp;amp;s[3..];letslice: &amp;amp;str =&amp;amp;s[..];字符串字面值的类型为字符串切片（&amp;amp;str）。
生存期 借用检查器会检查生存期长短关系，来保证借用安全。
fn main(){{letx=5;// ----------+-- &amp;#39;b // | letr=&amp;amp;x;// --+-- &amp;#39;a | // | | println!"><meta property="og:url" content="https://stardustdl.gitee.io/posts/learning/rust-onwership/"><meta property="og:site_name" content="StardustDL's Blog"><meta property="og:type" content="article"><meta property="article:section" content="Posts"><meta property="article:tag" content="Rust"><meta property="article:tag" content="编程语言"><meta property="article:published_time" content="2021-07-06T11:50:46+08:00"><meta property="article:modified_time" content="2021-07-06T11:50:46+08:00"><meta name=twitter:title content="Rust 所有权特性"><meta name=twitter:description content="规则  每个值都有一个称为其所有者的变量 同一时刻只能有一个所有者 当所有者离开作用域时，值被舍弃（调用 drop 函数）  变量与数据的交互 移动语义 Rust 从不自动进行变量的深层复制，而是使用移动语义。
lets1=String::from(&amp;#34;abc&amp;#34;);lets2=s1;// s1 is invalid 克隆语义 使用 clone 函数实现明确的深层复制。
lets1=String::from(&amp;#34;hello&amp;#34;);lets2=s1.clone();复制语义 诸如整数等类型数据，具有编译时已知的大小，并完全存储在栈上，能够快速复制，浅层复制与深层复制没有实际区别，不需要使用 clone 函数（实现 Copy 特征以标记这类数据）。
letx=5;lety=x;引用 lets1: String =String::from(&amp;#34;hello&amp;#34;);letref_s1: &amp;amp;String =&amp;amp;s1;letmutmut_s1: String =String::from(&amp;#34;hello&amp;#34;);letref_s1: &amp;amp;mutString=&amp;amp;mutmut_s1;&amp;amp; 表示引用变量，不取得变量的所有权，默认以不可变方式进行引用，&amp;amp;mut 表示可变方式引用。 传入引用变量的函数，称为借用了这个变量。
在同一作用域下，对同一个对象的引用，只允许以下组合方式：
 一个或多个不可变引用 一个可变引用，没有不可变引用  切片 切片指对一个序列中的一段连续元素的引用，不取得变量的所有权。
leta=[1,2,3,4,5];letslice=&amp;amp;a[1..3];assert_eq!(slice,&amp;amp;[2,3]);字符串切片 lets=String::from(&amp;#34;hello world&amp;#34;);lethello: &amp;amp;str =&amp;amp;s[0..5];letworld: &amp;amp;str =&amp;amp;s[6..11];letslice: &amp;amp;str =&amp;amp;s[..2];letslice: &amp;amp;str =&amp;amp;s[3..];letslice: &amp;amp;str =&amp;amp;s[..];字符串字面值的类型为字符串切片（&amp;amp;str）。
生存期 借用检查器会检查生存期长短关系，来保证借用安全。
fn main(){{letx=5;// ----------+-- &amp;#39;b // | letr=&amp;amp;x;// --+-- &amp;#39;a | // | | println!"><link rel="shortcut icon" href=/favicon.png><script type=application/javascript>var doNotTrack=!1;doNotTrack||(function(a,e,f,g,b,c,d){a.GoogleAnalyticsObject=b,a[b]=a[b]||function(){(a[b].q=a[b].q||[]).push(arguments)},a[b].l=1*new Date,c=e.createElement(f),d=e.getElementsByTagName(f)[0],c.async=1,c.src=g,d.parentNode.insertBefore(c,d)}(window,document,'script','https://www.google-analytics.com/analytics.js','ga'),ga('create','UA-111573521-1','auto'),ga('send','pageview'))</script></head><body class="article-page has-toc"><script>(function(){const a='StackColorScheme';localStorage.getItem(a)||localStorage.setItem(a,"auto")})()</script><script>(function(){const b='StackColorScheme',a=localStorage.getItem(b),c=window.matchMedia('(prefers-color-scheme: dark)').matches===!0;a=='dark'||a==='auto'&&c?document.documentElement.dataset.scheme='dark':document.documentElement.dataset.scheme='light'})()</script><div class="container main-container flex
extended"><div id=article-toolbar><a href=/ class=back-home><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-chevron-left" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><polyline points="15 6 9 12 15 18"/></svg><span>Back</span></a></div><main class="main full-width"><article class=main-article><header class=article-header><div class=article-details><header class=article-category><a href=/categories/learning/>Learning</a></header><h2 class=article-title><a href=/posts/learning/rust-onwership/>Rust 所有权特性</a></h2><footer class=article-time><div><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-calendar-time" width="56" height="56" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><path d="M11.795 21H5a2 2 0 01-2-2V7a2 2 0 012-2h12a2 2 0 012 2v4"/><circle cx="18" cy="18" r="4"/><path d="M15 3v4"/><path d="M7 3v4"/><path d="M3 11h16"/><path d="M18 16.496V18l1 1"/></svg><time class=article-time--published>Jul 06, 2021</time></div><div><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clock" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 15"/></svg><time class=article-time--reading>2 minute read</time></div></footer></div></header><section class=article-content><h1 id=规则>规则</h1><ul><li>每个值都有一个称为其所有者的变量</li><li>同一时刻只能有一个所有者</li><li>当所有者离开作用域时，值被舍弃（调用 <code>drop</code> 函数）</li></ul><h1 id=变量与数据的交互>变量与数据的交互</h1><h2 id=移动语义>移动语义</h2><p>Rust 从不自动进行变量的深层复制，而是使用移动语义。</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=kd>let</span><span class=w> </span><span class=n>s1</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=nb>String</span>::<span class=n>from</span><span class=p>(</span><span class=s>&#34;abc&#34;</span><span class=p>);</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>s2</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>s1</span><span class=p>;</span><span class=w> </span><span class=c1>// s1 is invalid
</span></code></pre></div><h2 id=克隆语义>克隆语义</h2><p>使用 <code>clone</code> 函数实现明确的深层复制。</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=kd>let</span><span class=w> </span><span class=n>s1</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=nb>String</span>::<span class=n>from</span><span class=p>(</span><span class=s>&#34;hello&#34;</span><span class=p>);</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>s2</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>s1</span><span class=p>.</span><span class=n>clone</span><span class=p>();</span><span class=w>
</span></code></pre></div><h2 id=复制语义>复制语义</h2><p>诸如整数等类型数据，具有编译时已知的大小，并完全存储在栈上，能够快速复制，浅层复制与深层复制没有实际区别，不需要使用 <code>clone</code> 函数（实现 <code>Copy</code> 特征以标记这类数据）。</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=kd>let</span><span class=w> </span><span class=n>x</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>5</span><span class=p>;</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>y</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>x</span><span class=p>;</span><span class=w>
</span></code></pre></div><h1 id=引用>引用</h1><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=kd>let</span><span class=w> </span><span class=n>s1</span>: <span class=nb>String</span> <span class=o>=</span><span class=w> </span><span class=nb>String</span>::<span class=n>from</span><span class=p>(</span><span class=s>&#34;hello&#34;</span><span class=p>);</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>ref_s1</span>: <span class=kp>&amp;</span><span class=nb>String</span> <span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>s1</span><span class=p>;</span><span class=w>
</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=k>mut</span><span class=w> </span><span class=n>mut_s1</span>: <span class=nb>String</span> <span class=o>=</span><span class=w> </span><span class=nb>String</span>::<span class=n>from</span><span class=p>(</span><span class=s>&#34;hello&#34;</span><span class=p>);</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>ref_s1</span>: <span class=kp>&amp;</span><span class=nc>mut</span><span class=w> </span><span class=nb>String</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=k>mut</span><span class=w> </span><span class=n>mut_s1</span><span class=p>;</span><span class=w>
</span></code></pre></div><p><code>&</code> 表示引用变量，不取得变量的所有权，默认以不可变方式进行引用，<code>&mut</code> 表示可变方式引用。
传入引用变量的函数，称为借用了这个变量。</p><p>在同一作用域下，对同一个对象的引用，只允许以下组合方式：</p><ul><li>一个或多个不可变引用</li><li>一个可变引用，没有不可变引用</li></ul><h1 id=切片>切片</h1><p>切片指对一个序列中的一段连续元素的引用，不取得变量的所有权。</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=kd>let</span><span class=w> </span><span class=n>a</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=p>[</span><span class=mi>1</span><span class=p>,</span><span class=w> </span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=mi>3</span><span class=p>,</span><span class=w> </span><span class=mi>4</span><span class=p>,</span><span class=w> </span><span class=mi>5</span><span class=p>];</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>slice</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>a</span><span class=p>[</span><span class=mi>1</span><span class=p>..</span><span class=mi>3</span><span class=p>];</span><span class=w>
</span><span class=w></span><span class=n>assert_eq</span><span class=o>!</span><span class=p>(</span><span class=n>slice</span><span class=p>,</span><span class=w> </span><span class=o>&amp;</span><span class=p>[</span><span class=mi>2</span><span class=p>,</span><span class=w> </span><span class=mi>3</span><span class=p>]);</span><span class=w>
</span></code></pre></div><h2 id=字符串切片>字符串切片</h2><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=kd>let</span><span class=w> </span><span class=n>s</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=nb>String</span>::<span class=n>from</span><span class=p>(</span><span class=s>&#34;hello world&#34;</span><span class=p>);</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>hello</span>: <span class=kp>&amp;</span><span class=kt>str</span> <span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>s</span><span class=p>[</span><span class=mi>0</span><span class=p>..</span><span class=mi>5</span><span class=p>];</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>world</span>: <span class=kp>&amp;</span><span class=kt>str</span> <span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>s</span><span class=p>[</span><span class=mi>6</span><span class=p>..</span><span class=mi>11</span><span class=p>];</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>slice</span>: <span class=kp>&amp;</span><span class=kt>str</span> <span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>s</span><span class=p>[..</span><span class=mi>2</span><span class=p>];</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>slice</span>: <span class=kp>&amp;</span><span class=kt>str</span> <span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>s</span><span class=p>[</span><span class=mi>3</span><span class=p>..];</span><span class=w>
</span><span class=w></span><span class=kd>let</span><span class=w> </span><span class=n>slice</span>: <span class=kp>&amp;</span><span class=kt>str</span> <span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>s</span><span class=p>[..];</span><span class=w>
</span></code></pre></div><p>字符串字面值的类型为字符串切片（<code>&str</code>）。</p><h1 id=生存期>生存期</h1><p>借用检查器会检查生存期长短关系，来保证借用安全。</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=k>fn</span> <span class=nf>main</span><span class=p>()</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>    </span><span class=p>{</span><span class=w>
</span><span class=w>        </span><span class=kd>let</span><span class=w> </span><span class=n>x</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=mi>5</span><span class=p>;</span><span class=w>            </span><span class=c1>// ----------+-- &#39;b
</span><span class=c1></span><span class=w>                              </span><span class=c1>//           |
</span><span class=c1></span><span class=w>        </span><span class=kd>let</span><span class=w> </span><span class=n>r</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=o>&amp;</span><span class=n>x</span><span class=p>;</span><span class=w>           </span><span class=c1>// --+-- &#39;a  |
</span><span class=c1></span><span class=w>                              </span><span class=c1>//   |       |
</span><span class=c1></span><span class=w>        </span><span class=n>println</span><span class=o>!</span><span class=p>(</span><span class=s>&#34;r: {}&#34;</span><span class=p>,</span><span class=w> </span><span class=n>r</span><span class=p>);</span><span class=w> </span><span class=c1>//   |       |
</span><span class=c1></span><span class=w>                              </span><span class=c1>// --+       |
</span><span class=c1></span><span class=w>    </span><span class=p>}</span><span class=w>                         </span><span class=c1>// ----------+
</span><span class=c1></span><span class=p>}</span><span class=w>
</span></code></pre></div><h2 id=标记生存期>标记生存期</h2><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=o>&amp;</span><span class=kt>i32</span><span class=w>        </span><span class=c1>// a reference
</span><span class=c1></span><span class=o>&amp;</span><span class=na>&#39;a</span><span class=w> </span><span class=kt>i32</span><span class=w>     </span><span class=c1>// a reference with an explicit lifetime
</span><span class=c1></span><span class=o>&amp;</span><span class=na>&#39;a</span><span class=w> </span><span class=k>mut</span><span class=w> </span><span class=kt>i32</span><span class=w> </span><span class=c1>// a mutable reference with an explicit lifetime
</span></code></pre></div><h2 id=函数中的生存期>函数中的生存期</h2><p>由于未标记生存期，以下代码无法编译：</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=k>fn</span> <span class=nf>longest</span><span class=p>(</span><span class=n>x</span>: <span class=kp>&amp;</span><span class=kt>str</span><span class=p>,</span><span class=w> </span><span class=n>y</span>: <span class=kp>&amp;</span><span class=kt>str</span><span class=p>)</span><span class=w> </span>-&gt; <span class=kp>&amp;</span><span class=kt>str</span> <span class=p>{</span><span class=w>
</span><span class=w>    </span><span class=k>if</span><span class=w> </span><span class=n>x</span><span class=p>.</span><span class=n>len</span><span class=p>()</span><span class=w> </span><span class=o>&gt;</span><span class=w> </span><span class=n>y</span><span class=p>.</span><span class=n>len</span><span class=p>()</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>        </span><span class=n>x</span><span class=w>
</span><span class=w>    </span><span class=p>}</span><span class=w> </span><span class=k>else</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>        </span><span class=n>y</span><span class=w>
</span><span class=w>    </span><span class=p>}</span><span class=w>
</span><span class=w></span><span class=p>}</span><span class=w>
</span></code></pre></div><p>报错如下。</p><pre><code>  |
9 | fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
  |               ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
  |
9 | fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
  |           ^^^^    ^^^^^^^     ^^^^^^^     ^^^
</code></pre><p>修正后的代码。</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=k>fn</span> <span class=nf>longest</span><span class=o>&lt;</span><span class=na>&#39;a</span><span class=o>&gt;</span><span class=p>(</span><span class=n>x</span>: <span class=kp>&amp;</span><span class=na>&#39;a</span><span class=w> </span><span class=kt>str</span><span class=p>,</span><span class=w> </span><span class=n>y</span>: <span class=kp>&amp;</span><span class=na>&#39;a</span><span class=w> </span><span class=kt>str</span><span class=p>)</span><span class=w> </span>-&gt; <span class=kp>&amp;</span><span class=na>&#39;a</span><span class=w> </span><span class=kt>str</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>    </span><span class=k>if</span><span class=w> </span><span class=n>x</span><span class=p>.</span><span class=n>len</span><span class=p>()</span><span class=w> </span><span class=o>&gt;</span><span class=w> </span><span class=n>y</span><span class=p>.</span><span class=n>len</span><span class=p>()</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>        </span><span class=n>x</span><span class=w>
</span><span class=w>    </span><span class=p>}</span><span class=w> </span><span class=k>else</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>        </span><span class=n>y</span><span class=w>
</span><span class=w>    </span><span class=p>}</span><span class=w>
</span><span class=w></span><span class=p>}</span><span class=w>
</span></code></pre></div><h2 id=结构中的生存期>结构中的生存期</h2><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=k>struct</span> <span class=nc>ImportantExcerpt</span><span class=o>&lt;</span><span class=na>&#39;a</span><span class=o>&gt;</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>    </span><span class=n>part</span>: <span class=kp>&amp;</span><span class=na>&#39;a</span><span class=w> </span><span class=kt>str</span><span class=p>,</span><span class=w>
</span><span class=w></span><span class=p>}</span><span class=w>
</span><span class=w>
</span><span class=w></span><span class=k>impl</span><span class=o>&lt;</span><span class=na>&#39;a</span><span class=o>&gt;</span><span class=w> </span><span class=n>ImportantExcerpt</span><span class=o>&lt;</span><span class=na>&#39;a</span><span class=o>&gt;</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>    </span><span class=k>fn</span> <span class=nf>level</span><span class=p>(</span><span class=o>&amp;</span><span class=bp>self</span><span class=p>)</span><span class=w> </span>-&gt; <span class=kt>i32</span> <span class=p>{</span><span class=w>
</span><span class=w>        </span><span class=mi>3</span><span class=w>
</span><span class=w>    </span><span class=p>}</span><span class=w>
</span><span class=w></span><span class=p>}</span><span class=w>
</span><span class=w>
</span><span class=w></span><span class=k>fn</span> <span class=nf>main</span><span class=p>()</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>    </span><span class=kd>let</span><span class=w> </span><span class=n>novel</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=nb>String</span>::<span class=n>from</span><span class=p>(</span><span class=s>&#34;Call me Ishmael. Some years ago...&#34;</span><span class=p>);</span><span class=w>
</span><span class=w>    </span><span class=kd>let</span><span class=w> </span><span class=n>first_sentence</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>novel</span><span class=p>.</span><span class=n>split</span><span class=p>(</span><span class=sc>&#39;.&#39;</span><span class=p>).</span><span class=n>next</span><span class=p>().</span><span class=n>expect</span><span class=p>(</span><span class=s>&#34;Could not find a &#39;.&#39;&#34;</span><span class=p>);</span><span class=w>
</span><span class=w>    </span><span class=kd>let</span><span class=w> </span><span class=n>i</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=n>ImportantExcerpt</span><span class=w> </span><span class=p>{</span><span class=w>
</span><span class=w>        </span><span class=n>part</span>: <span class=nc>first_sentence</span><span class=p>,</span><span class=w>
</span><span class=w>    </span><span class=p>};</span><span class=w>
</span><span class=w></span><span class=p>}</span><span class=w>
</span></code></pre></div><h2 id=生存期省略>生存期省略</h2><p>不标记生存期，编译器根据三个规则进行分析。</p><ol><li>每个引用参数赋予其自己独立的生存期。</li><li>如果只有一个生存期参数，则这个生存期赋予给返回值。</li><li>如果有多个生存期参数，但其中一个是 <code>self</code> 的引用（即方法），则 <code>self</code> 的生存期赋予给返回值。</li></ol><h2 id=静态生存期>静态生存期</h2><p>永久生存。</p><div class=highlight><pre class=chroma><code class=language-rust data-lang=rust><span class=kd>let</span><span class=w> </span><span class=n>s</span>: <span class=kp>&amp;</span><span class=nb>&#39;static</span><span class=w> </span><span class=kt>str</span><span class=w> </span><span class=o>=</span><span class=w> </span><span class=s>&#34;I have a static lifetime.&#34;</span><span class=p>;</span><span class=w>
</span></code></pre></div></section><footer class=article-footer><section class=article-tags><a href=/tags/rust/>Rust</a>
<a href=/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/>编程语言</a></section><section class=article-copyright><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-copyright" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><circle cx="12" cy="12" r="9"/><path d="M14.5 9a3.5 4 0 100 6"/></svg><span>Licensed under CC BY-NC-SA 4.0</span></section></footer><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.css integrity=sha384-RZU/ijkSsFbcmivfdRBQDtwuwVqK7GMOw6IMvKyeWL2K5UAlyp6WonmB8m7Jd0Hn crossorigin=anonymous><script src=https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.js integrity=sha384-pK1WpvzWVBQiP0/GjnvRxV4mOb0oxFuyRxJlk6vVw146n3egcN5C925NCP7a7BY8 crossorigin=anonymous defer></script><script src=https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/contrib/auto-render.min.js integrity=sha384-vZTG03m+2yp6N6BNi5iM4rW4oIwk5DfcNdFfxkk9ZWpDriOkXX8voJBFrAO7MpVl crossorigin=anonymous defer></script><script>window.addEventListener("DOMContentLoaded",()=>{renderMathInElement(document.querySelector(`.article-content`),{delimiters:[{left:"$$",right:"$$",display:!0},{left:"$",right:"$",display:!1},{left:"\\(",right:"\\)",display:!1},{left:"\\[",right:"\\]",display:!0}]})})</script></article><aside class=related-contents--wrapper><h2 class=section-title>Related contents</h2><div class=related-contents><div class="flex article-list--tile"><article><a href=/posts/learning/rust-functional/><div class=article-details><h2 class=article-title>Rust 函数式编程</h2></div></a></article><article><a href=/posts/learning/rust-generic-types/><div class=article-details><h2 class=article-title>Rust 泛型</h2></div></a></article><article><a href=/posts/learning/rust-collections/><div class=article-details><h2 class=article-title>Rust 集合</h2></div></a></article><article><a href=/posts/learning/rust-modules/><div class=article-details><h2 class=article-title>Rust 模块与项目</h2></div></a></article><article><a href=/posts/learning/rust-startup/><div class=article-details><h2 class=article-title>Rust 语言基础使用</h2></div></a></article></div></div></aside><script src=https://utteranc.es/client.js repo=StardustDL/stardustdl.github.io issue-term=pathname label=comment crossorigin=anonymous async></script><style>.utterances{max-width:unset}</style><script>function setUtterancesTheme(b){let a=document.querySelector('.utterances iframe');a&&a.contentWindow.postMessage({type:'set-theme',theme:`github-${b}`},'https://utteranc.es')}addEventListener('message',a=>{if(a.origin!=='https://utteranc.es')return;setUtterancesTheme(document.documentElement.dataset.scheme)}),window.addEventListener('onColorSchemeChange',a=>{setUtterancesTheme(a.detail)})</script><footer class=site-footer><section class=copyright>&copy;
2017 -
2021 StardustDL's Blog</section><section class=powerby><a style=color:gray href=http://www.beian.miit.gov.cn>冀ICP备19021004号</a><br>Built with <a href=https://gohugo.io/ target=_blank rel=noopener>Hugo</a><br>Theme <b><a href=https://github.com/CaiJimmy/hugo-theme-stack target=_blank rel=noopener data-version=3.5.0>Stack</a></b> designed by <a href=https://jimmycai.com target=_blank rel=noopener>Jimmy</a></section></footer><div class=pswp tabindex=-1 role=dialog aria-hidden=true><div class=pswp__bg></div><div class=pswp__scroll-wrap><div class=pswp__container><div class=pswp__item></div><div class=pswp__item></div><div class=pswp__item></div></div><div class="pswp__ui pswp__ui--hidden"><div class=pswp__top-bar><div class=pswp__counter></div><button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title=Share></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button><div class=pswp__preloader><div class=pswp__preloader__icn><div class=pswp__preloader__cut><div class=pswp__preloader__donut></div></div></div></div></div><div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"><div class=pswp__share-tooltip></div></div><button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button><div class=pswp__caption><div class=pswp__caption__center></div></div></div></div></div><script src=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js integrity="sha256-ePwmChbbvXbsO02lbM3HoHbSHTHFAeChekF1xKJdleo=" crossorigin=anonymous defer></script><script src=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js integrity="sha256-UKkzOn/w1mBxRmLLGrSeyB4e1xbrp4xylgAWb3M42pU=" crossorigin=anonymous defer></script><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css integrity="sha256-c0uckgykQ9v5k+IqViZOZKc47Jn7KQil4/MP3ySA3F8=" crossorigin=anonymous><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.css integrity="sha256-SBLU4vv6CA6lHsZ1XyTdhyjJxCjPif/TRkjnsyGAGnE=" crossorigin=anonymous></main><aside class="sidebar right-sidebar sticky"><section class="widget archives"><div class=widget-icon><svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-hash" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentcolor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z"/><line x1="5" y1="9" x2="19" y2="9"/><line x1="5" y1="15" x2="19" y2="15"/><line x1="11" y1="4" x2="7" y2="20"/><line x1="17" y1="4" x2="13" y2="20"/></svg></div><h2 class="widget-title section-title">Table of contents</h2><div class=widget--toc><nav id=TableOfContents><ol><li><a href=#规则>规则</a></li><li><a href=#变量与数据的交互>变量与数据的交互</a><ol><li><a href=#移动语义>移动语义</a></li><li><a href=#克隆语义>克隆语义</a></li><li><a href=#复制语义>复制语义</a></li></ol></li><li><a href=#引用>引用</a></li><li><a href=#切片>切片</a><ol><li><a href=#字符串切片>字符串切片</a></li></ol></li><li><a href=#生存期>生存期</a><ol><li><a href=#标记生存期>标记生存期</a></li><li><a href=#函数中的生存期>函数中的生存期</a></li><li><a href=#结构中的生存期>结构中的生存期</a></li><li><a href=#生存期省略>生存期省略</a></li><li><a href=#静态生存期>静态生存期</a></li></ol></li></ol></nav></div></section></aside></div><script src=https://cdn.jsdelivr.net/npm/node-vibrant@3.1.5/dist/vibrant.min.js integrity="sha256-5NovOZc4iwiAWTYIFiIM7DxKUXKWvpVEuMEPLzcm5/g=" crossorigin=anonymous defer></script><script type=text/javascript src=/ts/main.js defer></script><script>(function(){const a=document.createElement('link');a.href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&display=swap",a.type="text/css",a.rel="stylesheet",document.head.appendChild(a)})()</script></body></html>